package com.ourchem.bus.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ourchem.bus.service.NacosDataTokenService2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("nacosDataTokenService2")
public class NacosDataTokenService2Impl implements NacosDataTokenService2 {
    private final static Logger logger = LoggerFactory.getLogger(NacosDataTokenService2.class);

    private final static String TOKEN_KEY = "bpm:datacenter:token";
    private final static int EXPIRE_HOURS = 2;

    // private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    // private final ReadLock readLock = lock.readLock();
    // private final WriteLock writeLock = lock.writeLock();

    @Value("${datacenter.client.grant-type:client_credentials}")
    String grantType;

    @Value("${datacenter.client.client-id:}")
    String clientId;

    @Value("${datacenter.client.client-secret:}")
    String clientSecret;

    @Value("${datacenter.token-url:}")
    String tokenUrl;

    @Value("${datacenter.client.scope:select}")
    String scope;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public String getToken() {
        return requestToken();
    }

    @Override
    public String refreshToken() {
        delToken();
        return requestToken();
    }

    /**
     * 请求token
     * @return
     */
    // @Cacheable(value = TOKEN_KEY, key = "access_token", secondaryCache = @SecondaryCache(expireTime = EXPIRE_HOURS, timeUnit = TimeUnit.HOURS))
    public String requestToken() {
        // Object tokenObj = redisTemplate.opsForValue().get(TOKEN_KEY);
        String token = "";
        // if(Objects.isNull(tokenObj)) {
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", grantType);
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        params.put("scope", scope);
        params.put("refresh_token", "");
        HttpResponse response = HttpUtil.createGet(tokenUrl).form(params).execute();
        if(response.getStatus() == HttpStatus.HTTP_OK) {
            // logger.info("获取token成功！");
            // return JSON.parseObject(response.body()).getString("access_token");
            token = JSON.parseObject(response.body()).getString("access_token");
            // redisTemplate.opsForValue().set(TOKEN_KEY, token, EXPIRE_HOURS, TimeUnit.HOURS);
        } else {
            throw new RuntimeException(String.format("获取数据中心token失败：%s", response.toString()));
        }
        // } else {
        //     token = (String) tokenObj;
        // }
        return token;
    }

    // @CacheEvict(value = TOKEN_KEY)
    public void delToken() {
        redisTemplate.delete(TOKEN_KEY);
    }
}
